<template>
  <div class="app-container">
    <!-- 头部过滤部分  -->
    <div class="filter-container">
      <el-input v-model="listQuery.search" size="small" placeholder="模糊搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter">
        <i slot="prefix" class="el-input__icon el-icon-search" /></el-input>
      <el-select v-model="listQuery.roles" size="small" multiple placeholder="角色" clearable style="width: 200px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-if="checkPermission(['admin','user_create','user_all'])" class="filter-item" size="small" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>
    <!-- 表格部分 -->
    <div>
      <el-table
        v-if="checkPermission(['admin','user_list','user_all'])"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        size="small"
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像" width="60%">
          <template slot-scope="scope">
            <img :src="scope.row.image" class="el-avatar">
          </template>
        </el-table-column>
        <el-table-column label="用户名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            <template v-for="role in scope.row.roles">
              <span :key="role.id">{{ role.name }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.is_active | statusFilter">
              {{ row.is_active ? '激活':'锁定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button v-if="checkPermission(['admin','user_edit','user_all'])" type="primary" size="mini" :disabled="row.username === 'admin'" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button
              v-if="checkPermission(['admin','user_delete','user_all'])"
              slot="reference"
              :disabled="row.username === 'admin'"
              type="danger"
              size="mini"
              @click="handleDelete(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 编辑模态框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="700px">
      <el-form ref="dataForm" :rules="rules" :model="form" size="small" label-width="70px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" :disabled="dialogStatus === 'update'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="form.mobile" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="is_active">
              <el-radio-group v-model="form.is_active">
                <el-radio-button label="true">激活</el-radio-button>
                <el-radio-button label="false">锁定</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item style="margin-bottom: 0px;" label="角色">
              <template>
                <el-select v-model="roleIds" multiple placeholder="请选择">
                  <el-option
                    v-for="item in roles"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template></el-form-item>
          </el-col></el-row></el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, addUser, editUser, delUser } from '@/api/user'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { getRoles } from '@/api/role'
import checkPermission from '@/utils/permission'
import { isvalidPhone } from '@/utils/validate'

var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!isvalidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  name: 'User',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined,
        roles: [],
        sort: '+id'
      },
      roles: [],
      form: {
        id: undefined,
        username: '',
        name: '',
        mobile: '',
        email: '',
        is_active: 'true'
      },
      roleIds: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validPhone, trigger: 'blur' }
        ],
        is_active: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getRoleALL()
  },
  paramsSerializer: function(params) {
    const yourNewParams = params.roles.map(_ => `roles=${_}`).join('&')
    return yourNewParams
  },
  methods: {
    checkPermission,
    getList() {
      getUsers(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.roleIds = []
      this.form = {
        id: undefined,
        username: '',
        name: '',
        mobile: '',
        roles: [],
        email: '',
        is_active: 'true'
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      const _this = this
      this.roleIds.forEach(function(data, index) {
        _this.form.roles.push(data)
      })
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    getRoleALL() {
      getRoles().then(res => {
        this.roles = res
      })
    },
    handleUpdate(row) {
      this.resetForm()
      this.form = { ...row, roles: [] }
      // 赋值
      const _this = this
      row.roles.forEach(function(data, index) {
        _this.roleIds.push(data.id)
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      const _this = this
      this.roleIds.forEach(function(data, index) {
        _this.form.roles.push(data)
      })
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editUser(this.form.id, this.form).then(() => {
            for (const v of this.list) {
              if (v.id === this.form.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
